package cn.edu.njnu.opengmpback.recommendation.service.impl;

import cn.edu.njnu.opengmpback.common.utils.JsonResult;
import cn.edu.njnu.opengmpback.common.utils.ResultUtils;
import cn.edu.njnu.opengmpback.recommendation.client.DifyApiClient;
import cn.edu.njnu.opengmpback.recommendation.client.dto.DifyWorkflowRequest;
import cn.edu.njnu.opengmpback.recommendation.client.dto.DifyWorkflowResponse;
import cn.edu.njnu.opengmpback.recommendation.dto.request.RecommendationRequestDTO;
import cn.edu.njnu.opengmpback.recommendation.dto.response.RecommendationResponseDTO;
import cn.edu.njnu.opengmpback.recommendation.entity.RecommendedItem;
import cn.edu.njnu.opengmpback.recommendation.service.RecommendationService;
import cn.edu.njnu.opengmpback.resource.dao.ModelItemDao;
import cn.edu.njnu.opengmpback.resource.dao.ResourceDataDao;
import cn.edu.njnu.opengmpback.resource.entity.ModelItem;
import cn.edu.njnu.opengmpback.resource.entity.ResourceData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
@Slf4j
public class RecommendationServiceImpl implements RecommendationService {
    @Autowired
    DifyApiClient difyApiClient;

    @Autowired
    ResourceDataDao resourceDataDao;

    @Autowired
    ModelItemDao modelItemDao;

    @Override
    public JsonResult getRecommendation(RecommendationRequestDTO requestDTO) {
        try {
            log.info("开始获取推荐数据");

            // 1. 构建Dify工作流请求
            DifyWorkflowRequest workflowRequest = buildWorkflowRequest(requestDTO);

            // 2. 调用Dify API
            DifyWorkflowResponse workflowResponse = difyApiClient.executeWorkflow(workflowRequest);

            // 3. 转换为响应DTO
            RecommendationResponseDTO responseDTO = convertToResponse(workflowResponse, requestDTO);

            log.info("推荐数据获取成功");
            return ResultUtils.success(responseDTO);

        } catch (Exception e) {
            log.error("获取推荐数据失败", e);
            return ResultUtils.error(-1, "获取推荐数据失败");
        }
    }

    private DifyWorkflowRequest buildWorkflowRequest(RecommendationRequestDTO request) {
        DifyWorkflowRequest workflowRequest = new DifyWorkflowRequest();

        // 构建输入参数
        String query = request.getUserQuery();

        Map<String, Object> inputs = new HashMap<>();
        inputs.put("query", query);

        workflowRequest.setInputs(inputs);
        return workflowRequest;
    }

    private RecommendationResponseDTO convertToResponse(DifyWorkflowResponse workflowResponse,
                                                        RecommendationRequestDTO request) {
        RecommendationResponseDTO responseDTO = new RecommendationResponseDTO();
        DifyWorkflowResponse.Outputs outputs = workflowResponse.getData().getOutputs();
        // 从Dify响应中提取推荐数据
        if (outputs != null) {
            // 这里根据实际的Dify工作流输出格式进行转换
            // responseDTO.setRecommendations(...);
            String[] recommendationDataList = outputs.getData_list();
            String[] recommendationModelList = outputs.getModel_list();
            List<Object> recommendations = new ArrayList<>();

            if (recommendationDataList != null) {
                for ( String recommendationData : recommendationDataList ) {
                    ResourceData recommendation = resourceDataDao.findByName(recommendationData);
                    if (recommendation != null) { recommendations.add(recommendation); }

                }
            }
            if (recommendationModelList != null) {
                for ( String recommendationModel : recommendationModelList ) {
                    ModelItem recommendation = modelItemDao.findByName(recommendationModel);
                    if (recommendation != null) { recommendations.add(recommendation); }
                }
            }
            responseDTO.setRecommendations(recommendations);
        }

        return responseDTO;
    }

}
